from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List
from . import models, database
from pydantic import BaseModel
from datetime import datetime

router = APIRouter()


class OrderItemBase(BaseModel):
    product_id: int
    quantity: int


class OrderCreate(BaseModel):
    user_id: int
    items: List[OrderItemBase]


class OrderItem(OrderItemBase):
    id: int
    order_id: int
    price: float

    class Config:
        orm_mode = True


class Order(BaseModel):
    id: int
    user_id: int
    total_amount: float
    status: str
    created_at: datetime
    items: List[OrderItem] = []

    class Config:
        orm_mode = True


@router.post("/orders/", response_model=Order)
def create_order(order: OrderCreate, db: Session = Depends(database.get_db)):
    # 获取用户的购物车
    cart = db.query(models.Cart).filter(
        models.Cart.user_id == order.user_id).first()
    if not cart:
        raise HTTPException(status_code=404, detail="Cart not found")

    # 计算总金额
    total_amount = 0
    order_items = []

    for item in order.items:
        product = db.query(models.Product).filter(
            models.Product.id == item.product_id).first()
        if not product:
            raise HTTPException(
                status_code=404, detail=f"Product {item.product_id} not found")

        if product.stock < item.quantity:
            raise HTTPException(
                status_code=400, detail=f"Not enough stock for product {product.name}")

        # 更新库存
        product.stock -= item.quantity

        # 创建订单项
        order_item = models.OrderItem(
            product_id=item.product_id,
            quantity=item.quantity,
            price=product.price
        )
        order_items.append(order_item)
        total_amount += product.price * item.quantity

    # 创建订单
    db_order = models.Order(
        user_id=order.user_id,
        total_amount=total_amount,
        status="pending"
    )
    db.add(db_order)
    db.commit()
    db.refresh(db_order)

    # 添加订单项
    for item in order_items:
        item.order_id = db_order.id
        db.add(item)

    # 清空购物车
    db.query(models.CartItem).filter(
        models.CartItem.cart_id == cart.id).delete()

    db.commit()
    db.refresh(db_order)
    return db_order


@router.get("/orders/{order_id}", response_model=Order)
def get_order(order_id: int, db: Session = Depends(database.get_db)):
    order = db.query(models.Order).filter(models.Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="Order not found")
    return order


@router.get("/users/{user_id}/orders/", response_model=List[Order])
def get_user_orders(user_id: int, db: Session = Depends(database.get_db)):
    orders = db.query(models.Order).filter(
        models.Order.user_id == user_id).all()
    return orders


@router.put("/orders/{order_id}/status")
def update_order_status(order_id: int, status: str, db: Session = Depends(database.get_db)):
    order = db.query(models.Order).filter(models.Order.id == order_id).first()
    if not order:
        raise HTTPException(status_code=404, detail="Order not found")

    if status not in ["pending", "paid", "shipped", "delivered"]:
        raise HTTPException(status_code=400, detail="Invalid status")

    order.status = status
    db.commit()
    return {"message": "Order status updated successfully"}
